package com.blue.Impl.workflow;

import com.alibaba.fastjson.JSON;
import com.blue.common.exception.CustomException;
import com.blue.po.workflow.DefinitionPO;
import com.blue.service.workflow.IDefinitionService;
import com.blue.vo.workflow.DefinitionVO;
import com.blue.vo.workflow.NodeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.blue.mapper.workflow.InstanceMapper;
import com.blue.po.workflow.InstancePO;
import com.blue.service.workflow.IInstanceService;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
public class InstanceServiceImpl extends ServiceImpl<InstanceMapper, InstancePO> implements IInstanceService {

    @Autowired
    private IDefinitionService definitionService;

    @Override
    public void computeTime(List<InstancePO> instancePOS) {
        instancePOS.forEach(item -> {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (StringUtils.isNotBlank(item.getEndTime())) {
                LocalDateTime start = LocalDateTime.parse(item.getStartTime(), dateTimeFormatter);
                LocalDateTime end = LocalDateTime.parse(item.getEndTime(), dateTimeFormatter);
                Duration duration = Duration.between(start, end);
                long hours = duration.toHours();//相差的小时数
                long minutes = duration.toMinutes() % 60;//相差的分钟数
                item.setRetentionTime((hours == 0 ? "" : hours + "小时") + minutes + "分钟");
            }
        });
    }

    @Override
    public NodeVO getNodeInfo(String id) {
        InstancePO instancePO = this.getById(id);
        if (instancePO == null) {
            throw new CustomException("流程实例不存在！");
        }
        DefinitionPO definitionPO = definitionService.getById(instancePO.getDefinitionId());
        if (definitionPO == null) {
            throw new CustomException("流程定义不存在！");
        }
        String confJson = definitionPO.getConfJson();
        if(StringUtils.isBlank(confJson)){
            throw new CustomException("流程配置信息不能存在！");
        }
        DefinitionVO definitionVO = JSON.parseObject(confJson, DefinitionVO.class);
        return definitionVO.getNode();
    }
}
